<?php
// Rebuild Ressource Search Engine 
use Fox\Html\Input;
use Fox\Document;
use Fox\Dao\SqlFragment;
use Hive\Ressource;
use Fox\Html\Interval;
use Fox\Html\Block;
use Fox\Html\Screen;
set_time_limit(150000);
$screen = new Screen('bexe','execute');
$screen->pageTitle('Ressource Search Engine Synchronize');
$block = new Block('bExec','Parameters');
$block->add(new Interval('ressource_id',true));
$block->add(new Input('dbcnt',true,100));
$screen->add($block);

if($screen->submitted()) {
	
	$fields = $screen->get();
	if(!$screen->errors()) 
	{
		$commit = true;
		$fragments = $block->item('ressource_id')->fragments();
		
		$query = Fox\Databases::databases()->handle(Fox\Databases::DB_APP)->createQueryBuilder();
		$query->select('t.ressource_id','t.docid','d.filename','d.destination','d.physicalname')
			->from('ressource_documents','t')
			->innerJoin('t', 'documents','d','t.docid = d.docid')
			->setMaxResults($fields['dbcnt']);
		$fragments = is_array($fragments) ? $fragments : array($fragments);
		$fragments[] = new SqlFragment('t.docid > 5226');
		$fragment = SqlFragment::combine($fragments);
		$documents = $fragment->pushIn($query)->execute()->fetchAll(PDO::FETCH_ASSOC);
		if($commit) {
			$timer = new Fox\Debug\Timer();
			$timer->startRun();
			$searchEngine = new \Fox\SearchEngine();
			
			$grouping_type = Hive\Ressource::className();
			foreach($documents as $doc) {
				var_dump('rid:'.$doc['ressource_id'].' - docid:'.$doc['docid'].' - '.$doc['filename']);
				try {
					$document = Fox\Dao::load(Document::className(),$doc['docid']);
					$searchEngine->add($document,$doc['ressource_id'],$grouping_type);
					//$searchEngine->synchronize($document,$doc['ressource_id'],$grouping_type);
				}
				catch(Exception $e) {
					Fox\Message::Error($e->getMessage());
				}
				catch(Fox\Object\Exception\Save $e) {
					Fox\Message::Error($e->getMessage());
				}
				/*
				$extension = Document::extension($doc['filename']);
				$className = "Fox\\Document\\Reader\\".ucfirst($extension);
				$reader = new $className();
				$source = $doc['destination'].$doc['physicalname'];
				$content = $reader->read($source);
				*/
			}
		}
	}
}
echo $screen->display();